<template>
	<view :style="{'height':windowHeight, 'width':windowWidth, 'background-color':'#F1F1F1'}">
		<view class="login-header"></view>
		<view class="login-content">
			<uni-row>
				<uni-col :span="3">
					<view class="uni-col"></view>
				</uni-col>
				<uni-col :span="18">
					<view class="uni-col">
						<uni-forms ref="form" :modelValue="formData" label-position="top" :rules="userValidationRule">
							<uni-forms-item name="username">
								<uni-easyinput type="text" v-model="formData.username" placeholder="手机号" />
							</uni-forms-item>
							<uni-forms-item name="password">
								<uni-easyinput type="password" v-model="formData.password" placeholder="密码" />
							</uni-forms-item>
						</uni-forms>
					</view>
				</uni-col>
				<uni-col :span="3">
					<view class="uni-col"></view>
				</uni-col>
			</uni-row>
		</view>
		<view>
			<uni-row>
				<uni-col :span="3">
					<view class="uni-col"></view>
				</uni-col>
				<uni-col :span="8">
					<button class="uni-col button-font" @click="loginByPassword()">密码登录</button>
				</uni-col>
				<uni-col :span="2">
					<view class="uni-col"></view>
				</uni-col>
				<uni-col :span="8">
<!--					<button class="uni-col button-font"  open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" >微信登录</button>-->
					<button class="uni-col button-font" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">微信登录</button>
<!--					<button class="uni-col button-font"  @click="loginByWeixin()" >微信登录</button>-->
				</uni-col>
				<uni-col :span="3">
					<view class="uni-col"></view>
				</uni-col>
			</uni-row>
		</view>


	</view>
</template>

<script>

	export default {
		data() {
			return {
				windowHeight: '667px',
				windowWidth: '375px',
				formData: {
					username: '',
					password: ''
				},
				wxuserinfo: {
					nickname: '',
					phonenumber: '',
					iv: '',
					encryptedData: '',
					sessionKey: ''
				},
				userValidationRule: {
					username: {
						rules: [
							{
								required: true,
								errorMessage: '请输入手机号'
							},
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '长度标准不符合手机号特征'
							}
						]
					}
				},
			}
		},

		async onLoad() {

			// 系统信息
			uni.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight + "px";
					this.windowWidth = res.windowWidth + "px";
				}
			})


			await this.preGetPhonenumber()

		},
		methods: {

			/**
			 *
			 *	通过帐号密码进行登录
			 */
			loginByPassword() {
				this.$refs.form.validate().then((res) => {

				}).catch(err => {
					console.error('validator form data failed: ', err)
				})
			},

			async preGetPhonenumber() {
				// 授权
				await this.wxAuthorizePromise().catch((err) => {
					uni.showToast({
						icon: 'error',
						title: '用户授权失败！',
						duration: 3000
					})
				})

				// 微信用户登录
				var {loginCode} = await this.wxLoginPromise().then((res) => {
					return {
						loginCode: res.code,
					};
				})

				// 登录请求
				var {openId, sessionKey} = await this.uniRequest({
					url: '/login/wx',
					method: 'POST',
					data: {
						jsCode: loginCode,
					}
				}).then((res) => {
					return {
						openId: res.data.openId,
						sessionKey: res.data.sessionKey,
					}
				}).catch((err) => {
					console.error('登录请求后台接口错误: ', err)
					uni.showToast({
						icon: 'error',
						title: '登录请求失败！',
						duration: 3000
					})
				})

				this.globalData.OPEN_ID = openId
			},

			onGetPhoneNumber(e) {
				console.log('getphonenumber: ', e)
				uni.navigateTo({
					url: '/pages/main/Main?windowHeight=' + this.windowHeight + '&windowWidth=' + this.windowWidth
				})
			},

			/**
			 * 使用微信接口进行登录
			 */
			async loginByWeixin() {

				uni.navigateTo({
					url: '/pages/main/Main?windowHeight=' + this.windowHeight + '&windowWidth=' + this.windowWidth
				})

				/*

				await this.wxGetUserProfilePromise().then((res) => {
					this.wxuserinfo.nickname = res.userInfo.nickName
					this.wxuserinfo.encryptedData = res.encryptedData
					this.wxuserinfo.iv = res.iv
					console.log('wxuserinfo :', this.wxuserinfo)
				}).catch(err => {
					console.error('获取用户信息失败，失败原因：', err)
				})

				// 获取是否已开启“getUserInfo”权限
				let isOpenGetUserInfo = ''
				await this.authSettingsPromise().then((res) => {
					console.log('authSettings res:', res)
					isOpenGetUserInfo = res.authSetting['scope.userInfo']
				}).catch(err => {
					console.error('authSettings error:', err)
					uni.showToast({
						icon: 'error',
						title: '登录失败![获取授权设置调用失败] ',
						duration: 2000
					})
					return
				})

				// 未开启"getUserInfo", 则进行开启
				if (!isOpenGetUserInfo) {
					await this.wxAuthorizePromise()
				}

				// 微信用户登录
				let loginRes = ''
				await this.wxLoginPromise().then((res) => {
					loginRes = res
				})

				await this.uniRequest({
					url: '/login/wx',
					method: 'POST',
					data: {
						jsCode: loginRes.code,
					}
				}).then((res) => {
					this.globalData.OPEN_ID = res.data.openId;
					this.wxuserinfo.sessionKey = res.data.sessionKey;

					console.log('login success body:', res)

					console.log('wxuserinfo:', this.wxuserinfo)
					var securityFun = new WXBizDataCrypt(this.globalData.APP_ID, this.wxuserinfo.sessionKey)
					console.log('this.wxuserinfo.encryptedData:', this.wxuserinfo.encryptedData)
					console.log('this.wxuserinfo.iv', this.wxuserinfo.iv)
					var data = securityFun.decryptData(
							this.wxuserinfo.encryptedData,
							this.wxuserinfo.iv
					)
					console.log('解密后数据:', data)

					uni.navigateTo({
						url: '/pages/main/Main?windowHeight=' + this.windowHeight + '&windowWidth=' + this.windowWidth
					})
				}).catch(err => {
					console.error('登录后台调用发生错误:', err)
				})

				*/

			},

			/**
			 *
			 *  获取用户信息Function
			 *
			 */
			wxGetUserProfilePromise: function() {
				return new Promise((resolve, reject) => {
					wx.getUserProfile({
						desc: 'wexin',
						success: (res) => {
							console.log('User Profile: ', res)
							if (res.errMsg !== 'getUserProfile:ok') {
								return uni.showToast({
									icon: 'error',
									title: '获取用户信息失败! ',
									duration: 2000
								})
							}
							resolve(res)
						},
						fail: (err) => {
							uni.showToast({
								icon: 'error',
								title: '获取用户信息调用失败! ',
								duration: 2000
							})
							reject(err)
						}
					})

					// wx.getUserInfo({
					// 	provider: 'weixin',
					// 	success: (res) => {
					// 		console.log('get user info:', res)
					// 		resolve(res)
					// 	},
					// 	fail: (err) => {
					// 		console.error('get user info error:', err)
					// 		reject(err)
					// 	}
					// })
				})
			},

			/**
			 * 微信登录Function
			 *
			 */
			wxLoginPromise: function() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: (loginRes) => {
							if (loginRes.errMsg !== 'login:ok') {
								console.error('wx.login调用后返回值错误: ', loginRes)
								return uni.showToast({
									icon: 'error',
									title: '登录失败![wx.login调用后返回值错误] ',
									duration: 2000
								})
							}
							resolve(loginRes)
						},
						fail: (err) => {
							uni.showToast({
								icon: 'error',
								title: '登录失败![wx.login未成功调用] ',
								duration: 2000
							})
							console.error('wxLoginPromise err: ', err)
							reject(err)
						}
					})
				})
			},

			/**
			 * 获取用户设置 Function
			 * @returns {Promise<unknown>}
			 */
			authSettingsPromise: function() {
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success: (res) => {
							if (res.errMsg !== 'getSetting:ok') {
								console.log(res)
								return uni.showToast({
									icon: 'error',
									title: '登录失败![获取授权设置调用失败， 失败信息' + res.errMsg + '] ',
									duration: 2000
								})
							}
							resolve(res)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			/**
			 * 微信授权 Function
			 * @returns {Promise<unknown>}
			 */
			wxAuthorizePromise: function () {
				return new Promise((resolve, reject) => {
					uni.authorize({
						scope: 'scope.userInfo',
						success() {
							console.log("打开用户授权成功！")
							resolve();
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			}

		}
	}
</script>

<style>

	.login-header {
		/*background-color:#4cd964;*/
		height: 7rem;
	}
	.login-content {
		height: 13rem;
		/*background-color:#007aff;*/
	}

	.button-font {
		font-size: 15px;
	}


	.uni-col {
		height: 38px;
		border-radius: 4px;
	}

	.dark_deep {
		background-color: #99a9bf;
	}

	.dark {
		background-color: #d3dce6;
	}

	.light {
		background-color: #e5e9f2;
	}

	.wight {
		background-color: #ffffff;
	}

	.green {
		background-color: #4cd964;
	}

</style>
